package com.aikg.kgrag_java.utils;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JointBERT {
    public static String Bert(String command) {
        String requestUrl = "http://192.168.24.128:8092/predict";
        String jsonInputString = "{\"sentence\": \"" + command + "\"}";
        System.out.println(jsonInputString);
        String responseBody = "";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(requestUrl))
                .header("Content-Type", "application/json")
                .POST(BodyPublishers.ofString(jsonInputString))
                .build();

        try {
            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
//            System.out.println("Response status code: " + response.statusCode());
            responseBody = transfer(response.body());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    /**
     * 因为模型API返回值中的汉字是unicode编码，所以需要转化
     *
     * @param responce 模型的返回值
     * @return unicode编码转成汉字后的结果，并去掉了斜杠
     */
    public static String transfer(String responce) {

        // 正则表达式匹配Unicode转义序列
        Pattern pattern = Pattern.compile("\\\\u([0-9A-Fa-f]{4})");
        Matcher matcher = pattern.matcher(responce);

        // 使用 StringBuffer 来构建新的字符串
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            // 将匹配到的Unicode转义序列转换为对应的字符
            int codePoint = Integer.parseInt(matcher.group(1), 16);
            matcher.appendReplacement(result, String.valueOf(Character.toChars(codePoint)));
        }
        // 将最后的部分添加到字符串中
        matcher.appendTail(result);

        // 输出转换后的字符串
        return result.toString().replace("\\","");
    }


//    public static void main(String[] args) {
//        System.out.println(Bert("明天台湾天气怎么样"));
//    }
}
